#include "AutoControl.h"
#include "TinyXML/tinyxml.h"
#include "ChineseEnglishMapping.h"
#include <QDebug>
#include <QVBoxLayout>
#include <QSplitter>

AutoControl::AutoControl()
{

}

void AutoControl::InitUI(const QString &fileName, QList<QPair<QWidget *, QString> > &widgets, QMap<int, QList<TableWidgetForm *> > &m_pTableWidgetFormMap)
{
    QString filePath = QString("%1/config/%2/%3")
            .arg(COMMONS->XmlPath)
            .arg(COMMONS->MachType)
            .arg(fileName);
    QList<AtTimeStruct> AtTimeStructList;
    QList<AreaStruct> _AreaStructs;
    Analysis(filePath, AtTimeStructList, _AreaStructs);

    QWidget* widget = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(widget);

    widgets.append(qMakePair(widget,QStringLiteral("tab0")));

    TableWidgetForm* _TableWidgetForm = new TableWidgetForm(widget);
    layout->addWidget(_TableWidgetForm);
    _TableWidgetForm->setGroupBoxTitle(QString("%1_1").arg(fileName.left(fileName.size()-4)));
    if(AtTimeStructList.size() > 0)
    {
        AtTimeStruct _AtTimeStruct = AtTimeStructList.at(0);
        //获取表头
        _TableWidgetForm->setTableWidgetHeaderLabels(COMMONS->getTableWidgetHeadLabels(fileName,_AtTimeStruct.toFieldNames().split(',')));
        _TableWidgetForm->setTableWidgetHeaderType(_AtTimeStruct.toFieldTypes());

        for (int j = 0; j < AtTimeStructList.size(); j++)
        {
            _TableWidgetForm->getTableWidget()->setRowCount(j+1);
            _TableWidgetForm->getTableWidget()->setItem(j, 0, new QTableWidgetItem(AtTimeStructList.at(j).name));
            _TableWidgetForm->getTableWidget()->item(j, 0)->setData(Qt::UserRole, AtTimeStructList.at(j).id);
            _TableWidgetForm->getTableWidget()->setItem(j, 1, new QTableWidgetItem(QString("%1").arg(AtTimeStructList.at(j).initrotateswtime)));
            _TableWidgetForm->getTableWidget()->setItem(j, 2, new QTableWidgetItem(QString("%1").arg(AtTimeStructList.at(j).rotatejdtime)));
            _TableWidgetForm->getTableWidget()->setItem(j, 3, new QTableWidgetItem(QString("%1").arg(AtTimeStructList.at(j).defaults)));
        }
    }
    QList<TableWidgetForm*> item = m_pTableWidgetFormMap.value(0);
    m_pTableWidgetFormMap.insert(0, item << _TableWidgetForm);

    if(_AreaStructs.size() == 4)
    {
        for (int j = 0;j < 2;j++)
        {
            QWidget* widget = new QWidget;
            QVBoxLayout *layout = new QVBoxLayout(widget);
            QSplitter *splitter = new QSplitter(Qt::Vertical, widget);
            splitter->setChildrenCollapsible(false);
            layout->addWidget(splitter);
            widgets.append(qMakePair(widget, QStringLiteral("tab%1").arg(j+1)));
            for (int i = 0;i < 2;i++)
            {
                AreaStruct _AreaStruct = _AreaStructs.at(j*2+i);
                //表格1
                TableWidgetForm* _TableWidgetForm = new TableWidgetForm(widget);
                splitter->addWidget(_TableWidgetForm);
                _TableWidgetForm->setGroupBoxTitle(QString("%1_%2").arg(fileName.left(fileName.size()-4)).arg(j*4+i*2));

                //获取表头
                _TableWidgetForm->setTableWidgetHeaderLabels(COMMONS->getTableWidgetHeadLabels(fileName,_AreaStruct.toFieldNames().split(',')));
                _TableWidgetForm->setTableWidgetHeaderType(_AreaStruct.toFieldTypes());

                _TableWidgetForm->getTableWidget()->setRowCount(1);
                _TableWidgetForm->getTableWidget()->setItem(0, 0, new QTableWidgetItem(_AreaStruct.name));
                _TableWidgetForm->getTableWidget()->item(0, 0)->setData(Qt::UserRole, _AreaStruct.id);
                _TableWidgetForm->getTableWidget()->setItem(0, 1, new QTableWidgetItem(QString("%1").arg(_AreaStruct.reduce)));
                _TableWidgetForm->getTableWidget()->setItem(0, 2, new QTableWidgetItem(QString("%1").arg(_AreaStruct.invariant)));
                _TableWidgetForm->getTableWidget()->setItem(0, 3, new QTableWidgetItem(QString("%1").arg(_AreaStruct.initrotatepr)));
                _TableWidgetForm->getTableWidget()->setItem(0, 4, new QTableWidgetItem(QString("%1").arg(_AreaStruct.reducerotate)));
                _TableWidgetForm->getTableWidget()->setItem(0, 5, new QTableWidgetItem(QString("%1").arg(_AreaStruct.riserotate)));
                _TableWidgetForm->getTableWidget()->setItem(0, 6, new QTableWidgetItem(QString("%1").arg(_AreaStruct.lowlmit)));
                _TableWidgetForm->getTableWidget()->setItem(0, 7, new QTableWidgetItem(QString("%1").arg(_AreaStruct.uplmit)));

                //表格2
                TableWidgetForm* _TableWidgetForm2 = new TableWidgetForm(widget);
                splitter->addWidget(_TableWidgetForm2);
                _TableWidgetForm2->setGroupBoxTitle(QString("%1_%2").arg(fileName.left(fileName.size()-4)).arg(j*4+i*2+1));

                //获取表头
                softStruct _softStruct;
                _TableWidgetForm2->setTableWidgetHeaderLabels(COMMONS->getTableWidgetHeadLabels(fileName,_softStruct.toFieldNames().split(',')));
                _TableWidgetForm2->setTableWidgetHeaderType(_softStruct.toFieldTypes());

                for (auto item : _AreaStruct.softInfo)
                {
                    int rowCount = _TableWidgetForm2->getTableWidget()->rowCount();
                    _TableWidgetForm2->getTableWidget()->setRowCount(rowCount+1);
                    _TableWidgetForm2->getTableWidget()->setItem(rowCount, 0, new QTableWidgetItem(item.out_sensor));
                    _TableWidgetForm2->getTableWidget()->item(rowCount, 0)->setData(Qt::UserRole, item.soft_id);
                    _TableWidgetForm2->getTableWidget()->setItem(rowCount, 1, new QTableWidgetItem(QString("%1").arg(item.in_sensor)));
                }

                QList<TableWidgetForm*> item = m_pTableWidgetFormMap.value(j+1);
                m_pTableWidgetFormMap.insert(j+1, item << _TableWidgetForm << _TableWidgetForm2);
            }
        }
    }
}

bool AutoControl::SaveUI(const QString &fileName, const QMap<int, QList<TableWidgetForm *> > &m_pTableWidgetFormMap)
{
    QString filePath = QString("%1/config/%2/%3")
            .arg(COMMONS->XmlPath)
            .arg(COMMONS->MachType)
            .arg(fileName);
    if(m_pTableWidgetFormMap.count() == 3)
    {
        QList<AtTimeStruct> _AtTimeStructs;
        TableWidgetForm* _TableWidgetForm = m_pTableWidgetFormMap.value(0).at(0);
        if(_TableWidgetForm)
        {
            for(int k = 0;k<_TableWidgetForm->getTableWidget()->rowCount();k++)
            {
                AtTimeStruct _AtTimeStruct;
                _AtTimeStruct.id = _TableWidgetForm->getTableWidget()->item(k, 0)->data(Qt::UserRole).toInt();
                _AtTimeStruct.name = _TableWidgetForm->getTableWidget()->item(k, 0)->text();
                _AtTimeStruct.initrotateswtime = _TableWidgetForm->getTableWidget()->item(k, 1)->text().toInt();
                _AtTimeStruct.rotatejdtime = _TableWidgetForm->getTableWidget()->item(k, 2)->text().toInt();
                _AtTimeStruct.defaults = _TableWidgetForm->getTableWidget()->item(k, 3)->text().toInt();
                _AtTimeStructs.append(_AtTimeStruct);
            }
        }

        QList<AreaStruct> _AreaStructList;
        for(int i = 1;i<3;i++)
        {
            for (int j = 0;j<2;j++)
            {
                AreaStruct _AreaStruct;
                auto _TableWidgetForm = m_pTableWidgetFormMap.value(i).at(j*2);
                for(int k = 0;k<_TableWidgetForm->getTableWidget()->rowCount();k++)
                {
                    _AreaStruct.id = _TableWidgetForm->getTableWidget()->item(k,0)->data(Qt::UserRole).toInt();
                    _AreaStruct.name = _TableWidgetForm->getTableWidget()->item(k,0)->text();
                    _AreaStruct.reduce = _TableWidgetForm->getTableWidget()->item(k,1)->text().toDouble();
                    _AreaStruct.invariant = _TableWidgetForm->getTableWidget()->item(k,2)->text().toDouble();
                    _AreaStruct.initrotatepr = _TableWidgetForm->getTableWidget()->item(k,3)->text().toInt();
                    _AreaStruct.reducerotate = _TableWidgetForm->getTableWidget()->item(k,4)->text().toInt();
                    _AreaStruct.riserotate = _TableWidgetForm->getTableWidget()->item(k,5)->text().toInt();
                    _AreaStruct.lowlmit = _TableWidgetForm->getTableWidget()->item(k,6)->text().toInt();
                    _AreaStruct.uplmit = _TableWidgetForm->getTableWidget()->item(k,7)->text().toInt();
                }

                auto _TableWidgetForm2 = m_pTableWidgetFormMap.value(i).at(j*2+1);
                for (int k = 0;k<_TableWidgetForm2->getTableWidget()->rowCount();k++)
                {
                    softStruct _softStruct;
                    _softStruct.soft_id = _TableWidgetForm2->getTableWidget()->item(k,0)->data(Qt::UserRole).toInt();
                    _softStruct.out_sensor = _TableWidgetForm2->getTableWidget()->item(k,0)->text();
                    _softStruct.in_sensor = _TableWidgetForm2->getTableWidget()->item(k,1)->text().toInt();
                    _AreaStruct.softInfo.append(_softStruct);
                }
                _AreaStructList.append(_AreaStruct);
            }
        }
        AutoControl::SaveXml(filePath, _AtTimeStructs, _AreaStructList);
        return true;
    }
    return false;
}

void AutoControl::Analysis(const QString &path, QList<AtTimeStruct> &AtTimeStructMap, QList<AreaStruct> &_AreaStructs)
{
    TiXmlDocument* xmlDocument = new TiXmlDocument();
    if(!xmlDocument->LoadFile(path.toStdString().c_str()))
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return;
    }

    //查找xml文件中第一个名为Alarms的节点
    TiXmlElement* rootElement = xmlDocument->FirstChildElement("AutoControl");
    if(rootElement == nullptr) //节点不存在
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return;
    }

    if(rootElement)
    {
        TiXmlElement* AtTimeElement = rootElement->FirstChildElement("AtTime");
        if(AtTimeElement != nullptr)
        {
            for (TiXmlElement* AreaElement = AtTimeElement->FirstChildElement("Area");
                 AreaElement != nullptr; AreaElement = AreaElement->NextSiblingElement("Area")) {

                AtTimeStruct _AtTimeStruct;
                AreaElement->QueryIntAttribute("id", &_AtTimeStruct.id);
                _AtTimeStruct.name = AreaElement->Attribute("name");
                AreaElement->QueryIntAttribute("initrotateswtime", &_AtTimeStruct.initrotateswtime);
                AreaElement->QueryIntAttribute("rotatejdtime", &_AtTimeStruct.rotatejdtime);
                AreaElement->QueryIntAttribute("default", &_AtTimeStruct.defaults);

                AtTimeStructMap.append(_AtTimeStruct);
            }
        }

        for (TiXmlElement* AreaElement = rootElement->FirstChildElement("Area");
             AreaElement != nullptr; AreaElement = AreaElement->NextSiblingElement("Area")) {
            if(AreaElement != nullptr)
            {
                AreaStruct _AreaStruct;
                AreaElement->QueryIntAttribute("id", &_AreaStruct.id);
                _AreaStruct.name = AreaElement->Attribute("name");
                AreaElement->QueryDoubleAttribute("reduce", &_AreaStruct.reduce);
                AreaElement->QueryDoubleAttribute("invariant", &_AreaStruct.invariant);
                AreaElement->QueryIntAttribute("initrotatepr", &_AreaStruct.initrotatepr);
                AreaElement->QueryIntAttribute("reducerotate", &_AreaStruct.reducerotate);
                AreaElement->QueryIntAttribute("riserotate", &_AreaStruct.riserotate);
                AreaElement->QueryIntAttribute("lowlmit", &_AreaStruct.lowlmit);
                AreaElement->QueryIntAttribute("uplmit", &_AreaStruct.uplmit);

                for (TiXmlElement* FanElement = AreaElement->FirstChildElement("Fan");
                     FanElement != nullptr; FanElement = FanElement->NextSiblingElement("Fan")) {
                    softStruct _softStruct;
                    FanElement->QueryIntAttribute("soft_id", &_softStruct.soft_id);
                    _softStruct.out_sensor = FanElement->Attribute("out_sensor");
                    FanElement->QueryIntAttribute("in_sensor", &_softStruct.in_sensor);
                    _AreaStruct.softInfo.append(_softStruct);
                }
                _AreaStructs.append(_AreaStruct);
            }
        }
    }

    delete xmlDocument;
}

bool AutoControl::SaveXml(const QString &path, const QList<AtTimeStruct> &AtTimeStructList, const QList<AreaStruct> &_AreaStructList)
{
    TiXmlDocument* xmlDocument = new TiXmlDocument();
    if(!xmlDocument->LoadFile(path.toStdString().c_str()))
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return false;
    }

    //查找xml文件中第一个名为Person的节点
    TiXmlElement* rootElement = xmlDocument->FirstChildElement("AutoControl");
    if(rootElement == nullptr) //节点不存在
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return false;
    }

    if(rootElement)
    {
        TiXmlElement* AtTimeElement = rootElement->FirstChildElement("AtTime");
        if(AtTimeElement != nullptr)
        {
            for (TiXmlElement* AreaElement = AtTimeElement->FirstChildElement("Area");
                 AreaElement != nullptr; AreaElement = AreaElement->NextSiblingElement("Area"))
            {
                AtTimeElement->RemoveChild(AreaElement);
            }
            for (auto _AtTimeStruct : AtTimeStructList)
            {
                //元素类
                TiXmlElement* ChildxmlElement = new TiXmlElement("Area");
                ChildxmlElement->SetAttribute("id", _AtTimeStruct.id);
                ChildxmlElement->SetAttribute("name", _AtTimeStruct.name.toStdString().c_str());
                ChildxmlElement->SetAttribute("initrotateswtime", _AtTimeStruct.initrotateswtime);
                ChildxmlElement->SetAttribute("rotatejdtime", _AtTimeStruct.rotatejdtime);
                ChildxmlElement->SetAttribute("default", _AtTimeStruct.defaults);
                AtTimeElement->LinkEndChild(ChildxmlElement);
            }
        }

        int i = 0;
        for (TiXmlElement* AreaElement = rootElement->FirstChildElement("Area");
             AreaElement != nullptr; AreaElement = AreaElement->NextSiblingElement("Area")) {
            if(AreaElement != nullptr)
            {
                AreaElement->SetAttribute("id", _AreaStructList.at(i).id);
                AreaElement->SetAttribute("name", _AreaStructList.at(i).name.toStdString().c_str());
                AreaElement->SetAttribute("reduce", QString::number(_AreaStructList.at(i).reduce,'f',6).toStdString().c_str());
                AreaElement->SetAttribute("invariant", QString::number(_AreaStructList.at(i).invariant,'f',6).toStdString().c_str());
                AreaElement->SetAttribute("initrotatepr", _AreaStructList.at(i).initrotatepr);
                AreaElement->SetAttribute("reducerotate", _AreaStructList.at(i).reducerotate);
                AreaElement->SetAttribute("riserotate", _AreaStructList.at(i).riserotate);
                AreaElement->SetAttribute("lowlmit", _AreaStructList.at(i).lowlmit);
                AreaElement->SetAttribute("uplmit", _AreaStructList.at(i).uplmit);

                for (TiXmlElement* FanElement = AreaElement->FirstChildElement("Fan");
                     FanElement != nullptr; FanElement = FanElement->NextSiblingElement("Fan")) {
                    AreaElement->RemoveChild(FanElement);
                }
                for (auto _softStruct :_AreaStructList.at(i).softInfo)
                {
                    //元素类
                    TiXmlElement* ChildxmlElement = new TiXmlElement("Fan");
                    ChildxmlElement->SetAttribute("soft_id", _softStruct.soft_id);
                    ChildxmlElement->SetAttribute("out_sensor", _softStruct.out_sensor.toStdString().c_str());
                    ChildxmlElement->SetAttribute("in_sensor", _softStruct.in_sensor);
                    AreaElement->LinkEndChild(ChildxmlElement);
                }

                i++;
            }
        }
    }

    //保存
    xmlDocument->SaveFile(path.toStdString().c_str());

    delete xmlDocument;
    return true;
}
